package com.wyz.calibur.domain.user.service;

import cn.hutool.core.bean.BeanUtil;
import com.wyz.calibur.infrastructure.config.security.UserAuthInfo;
import com.wyz.calibur.infrastructure.db.role.mapper.RoleMapper;
import com.wyz.calibur.infrastructure.db.user.mapper.UserBaseInfoMapper;
import com.wyz.calibur.infrastructure.utils.JWTTokenUtil;
import com.wyz.calibur.pojo.user.UserBaseInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @Description:
 * @Author: wei yz
 * @Date: 2022/6/19 15:06
 */
@Service
public class UserAuthInfoServiceImpl implements UserAuthInfoService {
    private static final Logger log = LoggerFactory.getLogger(UserAuthInfoServiceImpl.class);

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserBaseInfoMapper userBaseInfoMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserBaseInfo user = userBaseInfoMapper.loadUserByUsername(s);
        if (BeanUtil.isEmpty(user)) {
            throw new UsernameNotFoundException("查询用户名[" + s + "]为空");
        }
        // 转换
        UserAuthInfo authInfo = new UserAuthInfo();
        // 模拟数据,锁、状态
        authInfo.setEnabled(true).setLocked(true);
        BeanUtils.copyProperties(user, authInfo);
        authInfo.setRoles(roleMapper.getRoleListByUserId(user.getId()));
        return authInfo;
    }

    @Override
    public String login(UserBaseInfo userBaseInfo) {
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(userBaseInfo.getUsername(), userBaseInfo.getPassword());
        Authentication authentication = authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = JWTTokenUtil.create(userBaseInfo.getUsername());
        return token;
    }
}
